import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:country_picker/country_picker.dart';
import 'package:life_milestones/MS-global-url.dart';
import 'package:life_milestones/MS-request.dart';
import 'package:life_milestones/controller/MS-global-user-controller.dart';
import 'package:stroke_text/stroke_text.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_picker/image_picker.dart';
import '../res/MS-country-list.dart';
import '../util/MS-log-util.dart';
import '../util/MS-toast-util.dart';
import '../util/MS-upload-file-util.dart';
import 'package:provider/provider.dart';

class MSEditPage extends StatefulWidget {
  const MSEditPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MSEditPageState();
  }
}

class _MSEditPageState extends State<MSEditPage> {
  late TextEditingController nickname;
  late TextEditingController birthday;
  late TextEditingController country;
  List<Country> countries = [];
  Country? current;
  @override
  initState() {
    super.initState();
    MSLog.addEvent(page:MSLogPages.Edit);
    nickname = TextEditingController(
        text: MSGlobalUserController().user?.nickname ?? "");
    birthday = TextEditingController(
        text: MSGlobalUserController().user?.birthday ?? "");
    countries = countryCodes.map((item) => Country.from(json: item)).toList();
    var target = countries
        .where((element) =>
            element.countryCode == MSGlobalUserController().user?.country)
        .toList();
    current = target.isNotEmpty ? target[0] : null;
    country =
        TextEditingController(text: target.isNotEmpty ? target[0].name : "");
  }

  pickImage(MSGlobalUserController controller) async {
    var status = await Permission.photos.status;
    if (status.isDenied) {
      if ((await Permission.photos.request()).isDenied) {
        showToast(
            "\"LifeMilestones\"  requires access to your album to post a record photo or update your personal avatar.");
        return;
      }
    }
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      showLoading();
      var path = await uploadFile(File(image.path));
      if (path != null) {
        MSRequest().post(MSGlobalUrl.updateAvatar,
            data: {"avatarPath": path}).then((value) {
              hideLoading();
          if (value["code"] == 0) {
            controller.refreshUserInfo();
            controller.setAvatarIsUpdated();
          }
        }).catchError((e){hideLoading();});
      }
    }
  }

  Future<bool> updateUserInfo(MSGlobalUserController controller) async {
    try {
      showLoading();
      var response = await MSRequest().post(MSGlobalUrl.updateUserInfo, data: {
        "about": "",
        "birthday": birthday.text,
        "country": current?.countryCode ?? "",
        "language": MSGlobalUserController().lang ?? "",
        "nickname": nickname.text
      });
      hideLoading();
      if (response["code"] == 0) {
        controller.refreshUserInfo();
        return true;
      }
    } catch (e) {
      hideLoading();
      return false;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MSGlobalUserController>(builder: (BuildContext context,
        MSGlobalUserController controller, Widget? child) {
      return Scaffold(
        resizeToAvoidBottomInset: false,
        body: SizedBox.expand(
          child: DecoratedBox(
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("images/mine-common-bg.png"))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  height: ScreenUtil().statusBarHeight + 57.w,
                  width: double.infinity,
                  padding: EdgeInsets.only(
                      top: ScreenUtil().statusBarHeight,
                      left: 24.w,
                      right: 24.w),
                  child: Stack(
                    children: [
                      Align(
                        alignment: Alignment.centerLeft,
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Image.asset(
                            "images/back.png",
                            width: 25.w,
                            fit: BoxFit.fitWidth,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.center,
                        child: Text(
                          "Edit information",
                          style: TextStyle(
                              fontSize: 20.sp,
                              color: const Color(0xFF333333),
                              fontWeight: FontWeight.w500),
                        ),
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 40.w),
                  child: InkWell(
                    onTap: () {
                      pickImage(controller);
                    },
                    child:SizedBox(
                            width: 109.w,
                            height: 104.w,
                            child: Stack(
                              children: [
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Container(
                                    width: 101.w,
                                    height: 101.w,
                                    decoration: BoxDecoration(
                                        borderRadius:
                                            BorderRadius.circular(15.w),
                                        border: Border.all(
                                            color: Color(0xFF148857),
                                            width: 2.w)),
                                    clipBehavior: Clip.antiAlias,
                                    child: Container(
                                      width: 99.w,
                                      height: 99.w,
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(15.w)),
                                      clipBehavior: Clip.antiAlias,
                                      child:!controller.checkAvatarIsUpdated() || controller.user?.avatarMiddleThumbUrl == null ? Image.asset(
                                        "images/avatar-placeholder.png",
                                        width: 101.w,
                                        height: 101.w,
                                        fit: BoxFit.cover,
                                      ):Image.network(
                                        controller.user!.avatarMiddleThumbUrl!,
                                        width: 101.w,
                                        height: 101.w,
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  ),
                                ),
                                Align(
                                  alignment: Alignment.bottomRight,
                                  child: Image.asset(
                                    "images/info-camera-yellow.png",
                                    width: 22.w,
                                    fit: BoxFit.fitWidth,
                                  ),
                                )
                              ],
                            ),
                          ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(
                    left: 30.w,
                    right: 30.w,
                    top: 50.w,
                  ),
                  child: Container(
                    height: 62.w,
                    width: double.infinity,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15.w)),
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    child: Row(
                      children: [
                        Image.asset(
                          "images/info-nick.png",
                          width: 28.w,
                          fit: BoxFit.fitWidth,
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          child: Container(
                            height: 17.w,
                            width: 2.w,
                            color: Color(0xFF70C37A),
                          ),
                        ),
                        Expanded(
                            child: TextField(
                          controller: nickname,
                          style: TextStyle(
                              fontSize: 16.sp,
                              color: Color(0xFF70C37A),
                              fontWeight: FontWeight.bold),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: "Nick Name",
                            hintStyle: TextStyle(
                                fontSize: 16.sp,
                                color: Color(0xFF999999),
                                fontWeight: FontWeight.w400),
                          ),
                          onChanged: (String value) {},
                        ))
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
                  child: Container(
                    height: 62.w,
                    width: double.infinity,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15.w)),
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    child: Row(
                      children: [
                        Image.asset(
                          "images/info-birthday.png",
                          width: 28.w,
                          fit: BoxFit.fitWidth,
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          child: Container(
                            height: 17.w,
                            width: 2.w,
                            color: Color(0xFF70C37A),
                          ),
                        ),
                        Expanded(child: Builder(
                          builder: (BuildContext context) {
                            return InkWell(
                              onTap: () {
                                showDatePicker(
                                        context: context,
                                        initialDate: DateTime.now(),
                                        firstDate: DateTime(1970),
                                        lastDate: DateTime.now(),
                                        initialDatePickerMode:
                                            DatePickerMode.year)
                                    .then((value) {
                                  if (value != null) {
                                    birthday.text =
                                        "${value.year}-${value.month + 1}-${value.day + 1}";
                                  }
                                });
                              },
                              child: TextField(
                                controller: birthday,
                                enabled: false,
                                style: TextStyle(
                                    fontSize: 16.sp,
                                    color: const Color(0xFF70C37A),
                                    fontWeight: FontWeight.bold),
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: "Date of Birth",
                                  hintStyle: TextStyle(
                                      fontSize: 16.sp,
                                      color: const Color(0xFF999999),
                                      fontWeight: FontWeight.w400),
                                ),
                                onChanged: (String value) {},
                              ),
                            );
                          },
                        ))
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
                  child: Container(
                    height: 62.w,
                    width: double.infinity,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15.w)),
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    child: Row(
                      children: [
                        Image.asset(
                          "images/info-country.png",
                          width: 28.w,
                          fit: BoxFit.fitWidth,
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          child: Container(
                            height: 17.w,
                            width: 2.w,
                            color: Color(0xFF70C37A),
                          ),
                        ),
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            showCountryPicker(
                                context: context,
                                onSelect: (Country c) {
                                  country.text = c.name;
                                  current = c;
                                });
                          },
                          child: TextField(
                            controller: country,
                            enabled: false,
                            style: TextStyle(
                                fontSize: 16.sp,
                                color: Color(0xFF70C37A),
                                fontWeight: FontWeight.bold),
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: "Country",
                              hintStyle: TextStyle(
                                  fontSize: 16.sp,
                                  color: Color(0xFF999999),
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ))
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 54.w),
                  child: InkWell(
                    onTap: () {
                      updateUserInfo(controller).then((value){
                        if(value){
                          Navigator.of(context).pop();
                        }
                      });
                    },
                    child: Container(
                      width: 219.w,
                      height: 51.w,
                      decoration: const BoxDecoration(
                          image: DecorationImage(
                              image:
                                  AssetImage("images/home-save-button-bg.png"),
                              fit: BoxFit.fill)),
                      alignment: Alignment.center,
                      child: StrokeText(
                        text: "Publish",
                        strokeWidth: 2.w,
                        textStyle: TextStyle(
                            fontSize: 20.sp,
                            color: const Color(0xFF333333),
                            fontWeight: FontWeight.bold),
                        strokeColor: Colors.white,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }
}
